<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769">
			<el-form ref="userDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="配置名称">
							<el-input v-model="state.ruleForm.name" placeholder="请输入配置名称" clearable ></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="变量名称">
							<el-input v-model="state.ruleForm.varName" placeholder="请输入变量名称" clearable :disabled="state.dialog.type==='edit'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="配置类型">
							<el-select v-model="state.ruleForm.type" placeholder="请选择" class="w100">
								<el-option v-for="item in state.types"
								:key="item.value"
								:label="item.label"
								:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="配置值" v-if="state.ruleForm.type===1">
							<el-input v-model="state.ruleForm.value" placeholder="请输入配置值" clearable type="textarea"></el-input>
						</el-form-item>
						<el-form-item label="配置值" v-else-if="state.ruleForm.type===2">
							<el-switch
							    v-model="state.ruleForm.value"
							    size="large"
								active-value="on"
								inactive-value="off"
							    active-text="on"
							    inactive-text="off"
								inline-prompt
							  />
						</el-form-item>
						<el-form-item label="上传图片" v-else-if="state.ruleForm.type===3">
							<el-upload
							    class="avatar-uploader"
							    :action="state.uploadImgUrl"
							    :show-file-list="false"
							    :on-success="handleUploadSuccess"
							    accept="image/*"
								:headers="state.header"
							  >
							    <img v-if="state.ruleForm.value" :src="state.ruleForm.value" class="avatar" />
							    <el-icon v-else class="avatar-uploader-icon" :size="30"><ele-Plus /></el-icon>
							  </el-upload>
						</el-form-item>
            <el-form-item label="上传视频" v-else-if="state.ruleForm.type===4">
              <div>
                <video :src="state.ruleForm.value" controls class="video" >
                  <source :src="state.ruleForm.value" />
                  不支持
                </video>
                <el-upload
                    class="video-uploader"
                    :action="state.uploadVideoUrl"
                    :show-file-list="true"
                    :on-success="handleUploadSuccess"
                    :on-remove="clearValue"
                    :file-list="state.fileList"
                    accept="video/*"
                    :headers="state.header"
                    limit="1"
                >
                  <el-button type="primary" size="default">上传视频</el-button>
                </el-upload>
              </div>
            </el-form-item>
            <el-form-item label="上传文件" v-else>
                <el-upload
                    class="file-uploader"
                    :action="state.uploadFileUrl"
                    :show-file-list="true"
                    :on-success="handleUploadSuccess"
                    :on-remove="clearValue"
                    :file-list="state.fileList"
                    accept="*/*"
                    :headers="state.header"
                    limit="1"
                >
                  <el-button type="primary" size="default">上传文件</el-button>
                </el-upload>
            </el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="配置描述">
							<el-input v-model="state.ruleForm.extension" placeholder="请输入描述" clearable type="textarea"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemUserDialog">
import { reactive, ref } from 'vue';
import { useConfigApi } from '/@/api/system/config';
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const baseUrl = import.meta.env.VITE_API_URL;
const state = reactive({
	ruleForm:<any> {
		id:0,//id
		name: '', // 配置名称
		varName: '', // 变量名称
		type: 1, // 配置值类型：1字符串，2开关，3图片，4视频，5文件
		value: '', // 配置值
		extension: '', // 描述
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	types: [
		{label:'文本',value:1},
		{label:'开关',value:2},
		{label:'图片',value:3},
		{label:'视频',value:4},
		{label:'文件',value:5},
	], // 配置值类型数组
	header:{Authorization:''},//上传请求头
	uploadImgUrl: baseUrl+'AdminUpload/image',//图片上传地址
	uploadVideoUrl: baseUrl+'AdminUpload/video',//视频上传地址
	uploadFileUrl: baseUrl+'AdminUpload/file',//文件上传地址
  fileList: [],//文件列表
});

//上传成功
const handleUploadSuccess = (
  response:any,
  uploadFile:any
) => {
	if(!response.code){
		state.ruleForm.value = response.data;
    state.fileList = [
      {name:uploadFile.name,url:response.data}
    ];
	}else{
		ElMessage.error(response.msg);
	}

}

//清除值
const clearValue = () => {
  state.ruleForm.value = '';
  state.fileList = [];
}
// 打开弹窗
const openDialog = (type: string, row: any) => {
  state.fileList = [];//清空图片列表
	if (type === 'edit') {

		var info = row;
		info = getFormData(info);
    //处理文件
    if(info.type > 2){
      state.fileList = [
        {name: info.value.substring(info.value.lastIndexOf('/')+1), url: info.value}
      ];
    }

		state.ruleForm = info;
		state.dialog.title = '修改配置';
		state.dialog.submitTxt = '修 改';
		state.dialog.type = 'edit';
	} else {
		state.dialog.title = '新增配置';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = 'add';
		// 清空表单
		state.ruleForm = {
      id:0,//id
      name: '', // 配置名称
      varName: '', // 变量名称
      type: 1, // 配置值类型：1字符串，2开关，3图片，4视频，5文件
      value: '', // 配置值
      extension: '', // 扩展配置值
    };
	}
	state.dialog.isShowDialog = true;

	state.header.Authorization = Session.get('token');
};
//填充提交数据
const getFormData = (data: any) => {
	var newData = {} as any,i;
	for(i in state.ruleForm){
		newData[i] = data[i];
	}

	return newData;
}
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
	useConfigApi().setAdminConfig(state.ruleForm).then(res=>{
		if(!res.code){
      // 清空表单
      state.ruleForm = {
        id:0,//id
        name: '', // 配置名称
        varName: '', // 变量名称
        type: 1, // 配置值类型：1字符串，2开关，3图片，4视频，5文件
        value: '', // 配置值
        extension: '', // 扩展配置值
      };
			ElMessage.success(state.dialog.title+'成功');
      closeDialog();
      emit('refresh');
		}
	}).catch(err=>{
		console.log(err);
	});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 30px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.video{
  width:300px;
  height: 180px;
  background-color: #000000;
}
.uploader-btn-box{
  margin-left: 20px;
}
.file-uploader{
  width:60%;
}
</style>
